package com.base.interceptor;


import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 功能限定哪些资源需要登录后才可以访问，哪些不需要登录就可以访问。
 *
 */
public class LoginCheckInterceptor implements HandlerInterceptor { 
	
	//包含不登录也可以访问的资源
	private static List<String> ALLOWEDSERVLETPATH = Arrays.asList("/login",
			"/notsupport","/logout","/password");

	/**
	 * 确定哪些资源在登录下才能访问，哪些资源不登录就可以访问
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String servletPath=request.getServletPath();
		String queryString=request.getQueryString();
		queryString=queryString==null ? "":("?"+queryString);
		//首先允许访问静态资源,和列表中的资源
		if(servletPath.startsWith("/resources/") || ALLOWEDSERVLETPATH.contains(servletPath)){
			return true;
		}else{
//			HttpSession session=request.getSession();
//			User user=(User) session.getAttribute("sessionUser");
//			if(user==null){
//				 String str = "<script type='text/javascript'>" + "window.top.location.href='"
//	                        + request.getContextPath()+"/login';</script>";
//	             response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
//	             try {
//                    PrintWriter writer = response.getWriter();
//                    writer.write(str);
//                    writer.flush();
//                    writer.close();
//                 } catch (Exception e) {
//                    e.printStackTrace();
//                 }
//				return false;
//			}else{
//				return true;
//			}
			request.setAttribute("currentPath", servletPath);
			return true;
		}
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception e)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView mv) throws Exception {
	}

}

